package com.example.config;

import com.example.client.Client;
import com.example.client.ClientServiceImpl;
import com.example.exception.ClientNotFoundException;
import com.example.user.User;
import com.example.user.UserServiceImpl;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import javax.annotation.Resource;

import static com.example.consts.InitialDataConst.*;

/**
 * @author wangbin
 */
@Configuration
@EnableAuthorizationServer
public class AuthConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private ClientServiceImpl clientServiceImpl;
    @Resource
    private UserServiceImpl userServiceImpl;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.passwordEncoder(passwordEncoder)
                .checkTokenAccess("isAuthenticated()")
        ;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .withClientDetails(clientServiceImpl)
        ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userServiceImpl)
                .tokenStore(new InMemoryTokenStore())
        ;
    }

    @Bean
    @Profile("!test")
    CommandLineRunner runner() {
        return args -> {
            try {
                clientServiceImpl.loadClientByClientId(CLIENT_ID);
            } catch (ClientNotFoundException e) {
                Client client = new Client();
                client.setClientId(CLIENT_ID);
                client.setClientSecret(passwordEncoder.encode(CLIENT_SECRET));
                client.setAuthorizedGrantTypeList("password,authorization_code,refresh_token");
                client.setRegisteredRedirectUriList("https://www.baidu.com");
                client.setScopeList("app");
                clientServiceImpl.save(client);
            }

            try {
                userServiceImpl.loadUserByUsername(USERNAME);
            } catch (RuntimeException e) {
                User user = new User();
                user.setUsername(USERNAME);
                user.setPassword(passwordEncoder.encode(PASSWORD));
                userServiceImpl.save(user);
            }
        };
    }
}
